/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.venta;

import Controller.VentaC;
import Controller.VentaDetalleC;
import Model.VentaDetalleM;
import Model.VentaM;
import MsSQL.ConMsSQL;
import Util.MiReloj;
import java.io.InputStream;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
public class frmEfectivoVuelto extends javax.swing.JDialog {

    private final String PDF = "PDF (*.pdf)";
    private final String DOC = "DOCX (*.docx)";
    private final String XLS = "Report (*.jrprint)";
    private final List<String> PERMITTED_FILE_TYPES_LIST = Arrays.asList(PDF, DOC, XLS);
    JDialog jDialogMostrar;
    private MiReloj oValidador;
    SimpleDateFormat formateador = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", new Locale("ES"));
    Date fechaDate = new Date();
    String fecha = formateador.format(fechaDate);
    private VentaM oM;
    private VentaDetalleM[] odetaM;
    int tienda;
    
    SimpleDateFormat formateador2 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a", new Locale("ES"));
    Date fechaDate2 = new Date();
    String fecha3 = formateador2.format(fechaDate2);
    
    @SuppressWarnings("CallToThreadStartDuringObjectConstruction")
    public frmEfectivoVuelto(java.awt.Frame parent, boolean modal, VentaM oVentaM, VentaDetalleM[] oDetalles) {
        super(parent, modal);
        initComponents();
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        configurarVentana(oVentaM, oDetalles);
        oValidador = new MiReloj(txtTotal, txtEfectivo, txtVuelto);
        oValidador.start();
        tienda = oVentaM.getIdTienda();
         
        
        
        
        txtEfectivo.requestFocus(); 
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnConfirmar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        txtVuelto = new javax.swing.JTextField();
        txtTotal = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtNroVenta = new javax.swing.JTextField();
        jLabel20 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        txtEfectivo = new javax.swing.JTextField();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cobro");

        btnConfirmar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnConfirmar.setText("CONFIRMAR");
        btnConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        txtVuelto.setBackground(new java.awt.Color(240, 240, 240));
        txtVuelto.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txtVuelto.setForeground(new java.awt.Color(102, 0, 0));
        txtVuelto.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtVuelto.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txtVuelto.setFocusable(false);
        txtVuelto.setOpaque(false);

        txtTotal.setEditable(false);
        txtTotal.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txtTotal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtTotal.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txtTotal.setOpaque(false);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Total Pago Efectivo      S/.");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Vuelto      S/.");

        txtNroVenta.setEditable(false);
        txtNroVenta.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txtNroVenta.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtNroVenta.setToolTipText("");
        txtNroVenta.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        txtNroVenta.setOpaque(false);

        jLabel20.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel20.setForeground(new java.awt.Color(0, 0, 102));
        jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel20.setText("Total       S/.");

        jLabel16.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel16.setForeground(new java.awt.Color(0, 0, 102));
        jLabel16.setText("No Venta:");

        txtEfectivo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtEfectivo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtEfectivoKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(txtNroVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtVuelto)
                    .addComponent(txtEfectivo)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtNroVenta, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtEfectivo, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtVuelto, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5))
        );

        btnCancelar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCancelar.setText("CANCELAR");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarActionPerformed
        if (!"".equals(txtVuelto.getText())) {
//            int rsp = JOptionPane.showConfirmDialog(null, "¿Desea realizar la venta?", "Mensaje de Dialogo", 0);
//            if (rsp == 0) {

                if (guardarVenta()) { 
                    
                    try {
                        int i = frmVenta.oModelTblas.getRowCount();
                        for (int a = 0; a < i + 1; a++) {
                            frmVenta.oModelTblas.removeRow(0);
                        }
                    } catch (Exception e) { }

                    frmVenta.txtSubTotal.setText("");
                    frmVenta.txtDescuento.setText("");
                    frmVenta.txtDesc.setText("");
                    frmVenta.txtIgv.setText("");
                    frmVenta.txtTotal.setText("");
                    frmVenta.txtCliente.setText("");
                    frmVenta.cbnDocumento.setSelectedIndex(0);
                    frmVenta.txtFecha.setText(fecha3);  
                    
                    calcularNroVenta oNroVenta = new calcularNroVenta(frmVenta.txtFecha.getText());
                    frmVenta.txtNroVenta.setText(oNroVenta.convertirNroventa());  
                    AbrirBoletaVenta();
                    this.dispose();

                } else {
                    JOptionPane.showMessageDialog(null, "Error al guardar");
                    this.dispose();
                }

//            } else {
//                this.dispose();
//            }
        }
        frmVenta.cargarModelo(tienda);
        
    }//GEN-LAST:event_btnConfirmarActionPerformed

    @SuppressWarnings("static-access")
    private void txtEfectivoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtEfectivoKeyReleased
        if (evt.getKeyCode() == evt.VK_ENTER) {
            btnConfirmar.requestFocus();
        }

        if (evt.getKeyCode() == evt.VK_TAB) {
            btnConfirmar.requestFocus();
        }

    }//GEN-LAST:event_txtEfectivoKeyReleased

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField txtEfectivo;
    private javax.swing.JTextField txtNroVenta;
    private javax.swing.JTextField txtTotal;
    private javax.swing.JTextField txtVuelto;
    // End of variables declaration//GEN-END:variables

    private void configurarVentana(VentaM oVentaM, VentaDetalleM[] detalleM) {
        txtTotal.setText(oVentaM.getTotal() + "");
        txtNroVenta.setText(oVentaM.getNumVenta());
        oM = oVentaM;
        odetaM = detalleM;
    }
        
    @SuppressWarnings({"CallToThreadDumpStack", "UseSpecificCatch"})
    private void AbrirBoletaVenta() {
        try {
            Connection conexion = ConMsSQL.obtenerConexion();
            ClassLoader cl = getClass().getClassLoader();
            InputStream in = cl.getClass().getResourceAsStream("/View/venta/rptBoleta.jasper");
            HashMap objHashMap = new HashMap();
            objHashMap.put("tienda", oM.getTienda());
            objHashMap.put("fecha", oM.getFecha());
            objHashMap.put("cliente", oM.getCliente());
            objHashMap.put("vendedor", oM.getVendedor());
            objHashMap.put("idventa", new VentaC().getIdVenta(oM.getNumVenta(),tienda));
            objHashMap.put("nroventa", oM.getNumVenta());
            objHashMap.put("subtotal", oM.getSubTotal());
            objHashMap.put("descuento", oM.getDescuento());
            objHashMap.put("igv", oM.getIgv());
            objHashMap.put("total", oM.getTotal());
            objHashMap.put("vuelto", Double.parseDouble(txtVuelto.getText()));
            objHashMap.put("efectivo", Double.parseDouble(txtEfectivo.getText()));
            objHashMap.put("logo", this.getClass().getResourceAsStream("/Image/BOLETA.png"));
            JasperPrint objJasperPrint = JasperFillManager.fillReport(in, objHashMap, conexion);
            JasperPrintManager.printReport(objJasperPrint, false);
             
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "No Existe Información para mostrar");
            e.printStackTrace();
        }
    }

    private boolean guardarVenta() {
        VentaC oC = new VentaC();
        VentaDetalleC oDetalleC = new VentaDetalleC();
        if (!oC.agregarVenta(oM)) {
            for (int i = 0; i < odetaM.length; i++) {
                odetaM[i].setIdVenta(new VentaC().getIdVenta(oM.getNumVenta(),tienda));
                if (oDetalleC.agregarVentaDetalle(odetaM[i])) {
                    new VentaDetalleC().actualizarStock(odetaM[i].getIdTienda(), odetaM[i].getIdPrenda());
                    return false;
                } else {
                    new VentaDetalleC().actualizarStock(odetaM[i].getIdTienda(), odetaM[i].getIdPrenda());
                }
            }

        } else {
            return false;
        }
        return true;
    }
}
